<?php

namespace App\Http\Controllers;

use App\Common\LinkFeedSeo;
use App\Models\LinkFeed;
use App\Models\Outgoing;
use App\Models\Program;
use App\Models\TrackUrlTemplate;
use App\Models\Website;
use App\Models\WebsiteLinkFeed;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use function array_shift;
use function count;
use function dd;
use function env;
use function in_array;
use function json_decode;
use function krsort;
use function mt_rand;
use function redirect;
use function str_replace;
use function urlencode;

class OutController extends Controller
{

    public function out(Request $request)
    {
        $ip = $request->getClientIp();
        $type = $request->get('t', '');
        //type=m是直接跳转到商家，l是直接跳转促销
        $value = $request->get('v', '');
        //merchantid
        $merchantId = $request->get('m', '');
        $websiteId = $request->get('wid', 0);
        if ($websiteId) {
            $websiteInfo = Website::where('id', $websiteId)->first();
        }
        if ($merchantId) {
            $merchantInfo = \App\Models\Merchant::where('id', $merchantId)->first();
        }
        $ebayAmazonUrl = $request->get('u', '');
        $outUrl = '';
        $direct = false;

        if ($merchantInfo) {
            $merchantInfo->out_url = 'https://' . $merchantInfo->root_domain;
        }
        if ($merchantInfo->handle_affiliate_id == -1) {
            $direct = true;
        }


        if ($merchantInfo->root_domain == 'online4baby.com') {
            $merchantInfo->out_url = 'https://www.online4baby.com';
        } elseif ($merchantInfo->root_domain == 'lightinthebox.com') {
            $merchantInfo->out_url = 'https://www.lightinthebox.com';
        } elseif ($merchantInfo->root_domain == 'barnesandnoble.com') {
            $merchantInfo->out_url = 'https://www.barnesandnoble.com';
        } elseif ($merchantInfo->root_domain == 'joann.com') {
            $merchantInfo->out_url = 'https://www.joann.com';
        } elseif ($merchantInfo->root_domain == 'sportsdirect.com') {
            $merchantInfo->out_url = 'https://www.sportsdirect.com';
        } elseif ($merchantInfo->root_domain == 'petsmart.com') {
            $merchantInfo->out_url = 'https://www.petsmart.com';
        } elseif ($merchantInfo->root_domain == 'sling.com') {
            $merchantInfo->out_url = 'https://www.sling.com';
        } elseif ($merchantInfo->root_domain == 'jdsports.co.uk') {
            $merchantInfo->out_url = 'https://www.jdsports.co.uk';
        } elseif ($merchantInfo->root_domain == 'netsuite.com') {
            $merchantInfo->out_url = 'https://www.netsuite.com';
        } elseif ($merchantInfo->root_domain == 'gucci.com') {
            $merchantInfo->out_url = 'https://www.gucci.com';
        } elseif ($merchantInfo->root_domain == 'safeway.com') {
            $merchantInfo->out_url = 'https://www.safeway.com';
        } elseif ($merchantInfo->root_domain == 'williams-sonoma.com') {
            $merchantInfo->out_url = 'https://www.williams-sonoma.com';
        } elseif ($merchantInfo->root_domain == 'westelm.com') {
            $merchantInfo->out_url = 'https://www.westelm.com';
        } elseif ($merchantInfo->root_domain == 'landsend.com') {
            $merchantInfo->out_url = 'https://www.landsend.com';
        } elseif ($merchantInfo->root_domain == 'razer.com') {
            $merchantInfo->out_url = 'https://www.razer.com';
        } elseif ($merchantInfo->root_domain == 'zennioptical.com') {
            $merchantInfo->out_url = 'https://www.zennioptical.com';
        } elseif ($merchantInfo->root_domain == 'newlook.com') {
            $merchantInfo->out_url = 'https://www.newlook.com';
        } elseif ($merchantInfo->root_domain == 'ringcentral.com') {
            $merchantInfo->out_url = 'https://www.ringcentral.com';
        } elseif ($merchantInfo->root_domain == 'gapfactory.com') {
            $merchantInfo->out_url = 'https://www.gapfactory.com';
        } elseif ($merchantInfo->root_domain == 'skillz.com') {
            $merchantInfo->out_url = 'https://www.skillz.com';
        } elseif ($merchantInfo->root_domain == 'lacoste.com') {
            $merchantInfo->out_url = 'https://www.lacoste.com';
        } elseif ($merchantInfo->root_domain == 'kobo.com') {
            $merchantInfo->out_url = 'https://www.kobo.com';
        } elseif ($merchantInfo->root_domain == 'sierra.com') {
            $merchantInfo->out_url = 'https://www.sierra.com';
        } elseif ($merchantInfo->root_domain == 'thebay.com') {
            $merchantInfo->out_url = 'https://www.thebay.com';
        } elseif ($merchantInfo->root_domain == 'parcelforce.com') {
            $merchantInfo->out_url = 'https://www.parcelforce.com';
        } elseif ($merchantInfo->root_domain == 'potterybarn.com') {
            $merchantInfo->out_url = 'https://www.potterybarn.com';
        } elseif ($merchantInfo->root_domain == 'dyson.com') {
            $merchantInfo->out_url = 'https://www.dyson.com';
        } elseif ($merchantInfo->root_domain == 'geappliances.com') {
            $merchantInfo->out_url = 'https://www.geappliances.com';
        } elseif ($merchantInfo->root_domain == 'burpee.com') {
            $merchantInfo->out_url = 'https://www.burpee.com';
        } elseif ($merchantInfo->root_domain == 'rugsusa.com') {
            $merchantInfo->out_url = 'https://www.rugsusa.com';
        } elseif ($merchantInfo->root_domain == 'mackenzie-childs.com') {
            $merchantInfo->out_url = 'https://www.mackenzie-childs.com';
        } elseif ($merchantInfo->root_domain == 'newair.com') {
            $merchantInfo->out_url = 'https://www.newair.com';
        } elseif ($merchantInfo->root_domain == '1800lighting.com') {
            $merchantInfo->out_url = 'https://www.1800lighting.com';
        } elseif ($merchantInfo->root_domain == 'apple.com') {
            $merchantInfo->out_url = 'https://www.apple.com';
        } elseif ($merchantInfo->root_domain == 'latam.com') {
            $merchantInfo->out_url = 'https://www.latam.com';
        } elseif ($merchantInfo->root_domain == 'lastpass.com') {
            $merchantInfo->out_url = 'https://www.lastpass.com';
        } elseif ($merchantInfo->root_domain == 'chime.com') {
            $merchantInfo->out_url = 'https://www.chime.com';
        } elseif ($merchantInfo->root_domain == 'mytheresa.com') {
            $merchantInfo->out_url = 'https://www.mytheresa.com';
        } elseif ($merchantInfo->root_domain == 'mybobs.com') {
            $merchantInfo->out_url = 'https://www.mybobs.com';
        } elseif ($merchantInfo->root_domain == 'manutd.com') {
            $merchantInfo->out_url = 'https://www.manutd.com';
        } elseif ($merchantInfo->root_domain == 'potterybarnkids.com') {
            $merchantInfo->out_url = 'https://www.potterybarnkids.com';
        } elseif ($merchantInfo->root_domain == 'sony.co.uk') {
            $merchantInfo->out_url = 'https://www.sony.co.uk';
        } elseif ($merchantInfo->root_domain == 'appliancesdirect.co.uk') {
            $merchantInfo->out_url = 'https://www.appliancesdirect.co.uk';
        } elseif ($merchantInfo->root_domain == 'birkenstock.com') {
            $merchantInfo->out_url = 'https://www.birkenstock.com';
        } elseif ($merchantInfo->root_domain == 'laptopsdirect.co.uk') {
            $merchantInfo->out_url = 'https://www.laptopsdirect.co.uk';
        } elseif ($merchantInfo->root_domain == 'farmrio.com.br') {
            $merchantInfo->out_url = 'https://www.farmrio.com.br';
        } elseif ($merchantInfo->root_domain == 'audiobooks.com') {
            $merchantInfo->out_url = 'https://www.audiobooks.com';
        } elseif ($merchantInfo->root_domain == 'catofashions.com') {
            $merchantInfo->out_url = 'https://www.catofashions.com';
        } elseif ($merchantInfo->root_domain == 'sandro-paris.com') {
            $merchantInfo->out_url = 'https://www.sandro-paris.com';
        } elseif ($merchantInfo->root_domain == 'petbarn.com.au') {
            $merchantInfo->out_url = 'https://www.petbarn.com.au';
        } elseif ($merchantInfo->root_domain == 'llbean.com') {
            $merchantInfo->out_url = 'https://www.llbean.com';
        } elseif ($merchantInfo->root_domain == 'priceline.com') {
            $merchantInfo->out_url = 'https://www.priceline.com';
        } elseif ($merchantInfo->root_domain == 'advanceautoparts.com') {
            $merchantInfo->out_url = 'https://www.advanceautoparts.com';
        } elseif ($merchantInfo->root_domain == 'eyebuydirect.com') {
            $merchantInfo->out_url = 'https://www.eyebuydirect.com';
        } elseif ($merchantInfo->root_domain == 'uhaul.com') {
            $merchantInfo->out_url = 'https://www.uhaul.com';
        } elseif ($merchantInfo->root_domain == 'brownells.com') {
            $merchantInfo->out_url = 'https://www.brownells.com';
        } elseif ($merchantInfo->root_domain == 'kroger.com') {
            $merchantInfo->out_url = 'https://www.kroger.com';
        } elseif ($merchantInfo->root_domain == 'currys.co.uk') {
            $merchantInfo->out_url = 'https://www.currys.co.uk';
        } elseif ($merchantInfo->root_domain == 'houseoffraser.co.uk') {
            $merchantInfo->out_url = 'https://www.houseoffraser.co.uk';
        } elseif ($merchantInfo->root_domain == 'containerstore.com') {
            $merchantInfo->out_url = 'https://www.containerstore.com';
        } elseif ($merchantInfo->root_domain == 'nuts.com') {
            $merchantInfo->out_url = 'https://www.nuts.com';
        } elseif ($merchantInfo->root_domain == 'duluthtrading.com') {
            $merchantInfo->out_url = 'https://www.duluthtrading.com';
        } elseif ($merchantInfo->root_domain == 'vitaminshoppe.com') {
            $merchantInfo->out_url = 'https://www.vitaminshoppe.com';
        } elseif ($merchantInfo->root_domain == 'teleflora.com') {
            $merchantInfo->out_url = 'https://www.teleflora.com';
        } elseif ($merchantInfo->root_domain == 'redbubble.com') {
            $merchantInfo->out_url = 'https://www.redbubble.com';
        } elseif ($merchantInfo->root_domain == 'gnc.com') {
            $merchantInfo->out_url = 'https://www.gnc.com';
        } elseif ($merchantInfo->root_domain == 'clarks.co.uk') {
            $merchantInfo->out_url = 'https://www.clarks.co.uk';
        } elseif ($merchantInfo->root_domain == 'superdry.co.uk') {
            $merchantInfo->out_url = 'https://www.superdry.co.uk';
        } elseif ($merchantInfo->root_domain == 'superdry.com') {
            $merchantInfo->out_url = 'https://www.superdry.com';
        } elseif ($merchantInfo->root_domain == 'lakeland.co.uk') {
            $merchantInfo->out_url = 'https://www.lakeland.co.uk';
        } elseif ($merchantInfo->root_domain == 'cottontraders.co.uk') {
            $merchantInfo->out_url = 'https://www.cottontraders.co.uk';
        } elseif ($merchantInfo->root_domain == 'ikea.com') {
            $merchantInfo->out_url = 'https://www.ikea.com';
        } elseif ($merchantInfo->root_domain == 'pandaexpress.com') {
            $merchantInfo->out_url = 'https://www.pandaexpress.com';
        } elseif ($merchantInfo->root_domain == 'dunhamssports.com') {
            $merchantInfo->out_url = 'https://www.dunhamssports.com';
        } elseif ($merchantInfo->root_domain == 'runningwarehouse.com') {
            $merchantInfo->out_url = 'https://www.runningwarehouse.com';
        } elseif ($merchantInfo->root_domain == 'adorama.com') {
            $merchantInfo->out_url = 'https://www.adorama.com';
        } elseif ($merchantInfo->root_domain == 'bobevans.com') {
            $merchantInfo->out_url = 'https://www.bobevans.com';
        } elseif ($merchantInfo->root_domain == 'buildabear.com') {
            $merchantInfo->out_url = 'https://www.buildabear.com';
        } elseif ($merchantInfo->root_domain == 'panerabread.com') {
            $merchantInfo->out_url = 'https://www.panerabread.com';
        } elseif ($merchantInfo->root_domain == 'pureformulas.com') {
            $merchantInfo->out_url = 'https://www.pureformulas.com';
        } elseif ($merchantInfo->root_domain == 'hammacher.com') {
            $merchantInfo->out_url = 'https://www.hammacher.com';
        } elseif ($merchantInfo->root_domain == 'christmastreeshops.com') {
            $merchantInfo->out_url = 'https://www.christmastreeshops.com';
        } elseif ($merchantInfo->root_domain == 'uncommongoods.com') {
            $merchantInfo->out_url = 'https://www.uncommongoods.com';
        } elseif ($merchantInfo->root_domain == 'monoprice.com') {
            $merchantInfo->out_url = 'https://www.monoprice.com';
        } elseif ($merchantInfo->root_domain == 'newlook.co.uk') {
            $merchantInfo->out_url = 'https://www.newlook.co.uk';
        } elseif ($merchantInfo->root_domain == 'hayneedle.com') {
            $merchantInfo->out_url = 'https://www.hayneedle.com';
        } elseif ($merchantInfo->root_domain == 'mandmdirect.co.uk') {
            $merchantInfo->out_url = 'https://www.mandmdirect.co.uk';
        } elseif ($merchantInfo->root_domain == 'fatface.com') {
            $merchantInfo->out_url = 'https://www.fatface.com';
        } elseif ($merchantInfo->root_domain == 'scholastic.com') {
            $merchantInfo->out_url = 'https://www.scholastic.com';
        } elseif ($merchantInfo->root_domain == 'whitehouseblackmarket.com') {
            $merchantInfo->out_url = 'https://www.whitehouseblackmarket.com';
        } elseif ($merchantInfo->root_domain == 'dieffematic.com') {
            $merchantInfo->out_url = 'https://www.dieffematic.com';
        } elseif ($merchantInfo->root_domain == 'yota.ru') {
            $merchantInfo->out_url = 'https://www.yota.ru';
        } elseif ($merchantInfo->root_domain == 'ganz.com') {
            $merchantInfo->out_url = 'https://www.ganz.com';
        } elseif ($merchantInfo->root_domain == 'idraulicagruppoober.it') {
            $merchantInfo->out_url = 'https://www.idraulicagruppoober.it';
        } elseif ($merchantInfo->root_domain == 'aisilbagno.it') {
            $merchantInfo->out_url = 'https://www.aisilbagno.it';
        } elseif ($merchantInfo->root_domain == 'tenergy.com') {
            $merchantInfo->out_url = 'https://www.tenergy.com';
        } elseif ($merchantInfo->root_domain == 'hotelscombined.com.tw') {
            $merchantInfo->out_url = 'https://www.hotelscombined.com.tw';
        }

        $ipFilters = config('black.ip');

        if ($websiteId == 120) {
            foreach ($ipFilters as $ipFilter) {
                if (stristr($ipFilter, $ip)) {
                    sleep(120);
                    return abort(404);
                }

            }
        }

        $subTracking = Str::random(64);
        $ids = json_decode($websiteInfo->affiliate_ids, true);

        if ($ids) {
            if ($merchantInfo->handle_affiliate_merchant) {
                $programs = Program::where('merchant_id', $merchantInfo->handle_affiliate_merchant)->where('status_in_affiliate',
                    Program::ACTIVE_IN_AFF)->whereIn('affiliate_id', $ids)->where('status_in_dashboard',
                    Program::ACTIVE_IN_DASHBOARD)->groupBy('affiliate_id')->get();
            } else {
                $programs = Program::where('merchant_id', $merchantId)->where('status_in_affiliate',
                    Program::ACTIVE_IN_AFF)->whereIn('affiliate_id', $ids)->where('status_in_dashboard',
                    Program::ACTIVE_IN_DASHBOARD)->groupBy('affiliate_id')->get();
            }

        } else {
            if ($merchantInfo->handle_affiliate_merchant) {
                $programs = Program::where('merchant_id', $merchantInfo->handle_affiliate_merchant)->where('status_in_affiliate',
                    Program::ACTIVE_IN_AFF)->where('affiliate_id', 1)->where('status_in_dashboard',
                    Program::ACTIVE_IN_DASHBOARD)->groupBy('affiliate_id')->get();
            } else {
                $programs = Program::where('merchant_id', $merchantId)->where('status_in_affiliate',
                    Program::ACTIVE_IN_AFF)->where('affiliate_id', 1)->where('status_in_dashboard',
                    Program::ACTIVE_IN_DASHBOARD)->groupBy('affiliate_id')->get();
            }

        }

        $count = $programs->count();
        $deepUrl = '';

        foreach ($programs as $program) {
            $levelPrograms[$program->affiliate->level][] = $program;
        }

        if ($levelPrograms) {
            krsort($levelPrograms);
            $firstLevels = array_shift($levelPrograms);
            if (count($firstLevels) == 1) {
                $index = 0;
            } else {
                $index = mt_rand(0, count($firstLevels) - 1);
            }
            $affiliateId = $firstLevels[$index]->affiliate_id;
            $trackUrl = $firstLevels[$index]->track_url;

        } else {
            $affiliateId = 1;
        }


        if (!$trackUrl) {
            if (($affiliateId == 8)) {
                if (($websiteInfo->skimlinks_id)) {
                    $trackUrl = "https://go.skimresources.com?id={$websiteInfo->skimlinks_id}&xs=1&url=[DEEPURL]&xcust=[SUBTRACKING]";
                } else {
                    $trackUrl = "https://redirect.viglink.com?key=99864b4f8f71776ad32e87fd0fc34fd9&u=[DEEPURL]&cuid=[SUBTRACKING]&opt=true";
                    $affiliateId = 1;
                }
            } else {
                $trackUrl = TrackUrlTemplate::where('affiliate_id', $affiliateId)->first();
                $trackUrl = $trackUrl->template;
            }
        }

        switch ($type) {
            case 'm':
                $deepUrl = $merchantInfo->out_url;

                break;
            case 'l':
                $linkFeed = WebsiteLinkFeed::where('id', $value)->first();
                if ($linkFeed->url) {
                    $deepUrl = urlencode($linkFeed->url);
                } elseif ($linkFeed->affiliate_url) {
                    $mainLinkFeed = LinkFeed::where('id', $linkFeed->linkfeed_id)->first();
                    if (in_array($mainLinkFeed->affiliate_id, $ids)) {
                        $outUrl = $linkFeed->affiliate_url;
                        $affiliateId = $mainLinkFeed->affiliate_id;
                    }
                }
                break;
        }
        if ($deepUrl && $trackUrl) {
            $outUrl = str_replace('[DEEPURL]', $deepUrl, $trackUrl);
            $outUrl = str_replace('[SUBTRACKING]', $subTracking, $outUrl);
        } elseif ($outUrl) {
            $outUrl = str_replace('[SUBTRACKING]', $subTracking, $outUrl);
        }


        if (!$outUrl && $trackUrl) {
            $outUrl = str_replace('[DEEPURL]', $merchantInfo->out_url, $trackUrl);
            $outUrl = str_replace('[SUBTRACKING]', $subTracking, $outUrl);
        } elseif (!$outUrl && !$trackUrl) {
            $outUrl = "https://redirect.viglink.com?key=99864b4f8f71776ad32e87fd0fc34fd9&u={$merchantInfo->out_url}&cuid={$subTracking}&opt=true";
            $affiliateId = 1;
        }

        if (!$outUrl) {
            $outUrl = "https://redirect.viglink.com?key=99864b4f8f71776ad32e87fd0fc34fd9&u={$merchantInfo->out_url}&cuid={$subTracking}&opt=true";
            $affiliateId = 1;
        }


        $cookies = $request->cookie();
        $data['out_url'] = $outUrl;
        $data['is_competitor'] = 0;
        $data['affiliate_id'] = $affiliateId;
        $data['merchant_id'] = $merchantId;
        $data['ip'] = $request->getClientIp();
        $data['value_id'] = $value;
        $data['user_agent'] = $request->userAgent();
        $data['type'] = $type;
        $data['sid'] = $subTracking;
        $data['from'] = 0;
        $data['created_at'] = now();
        $data['updated_at'] = now();
        $data['website_id'] = $websiteId;

        if ($request->get('xoxo')) {
            dd($data);
        }

        if (!isset($cookies['GO_OUTING'])) {

            Outgoing::insert($data);
        }


        return redirect(null, 302, ['referer' => env('APP_URL')])->away(($outUrl));
    }

}
